<?php
/**
* @file AuthenticationService.php
* Copyright (c) Friends Group. All rights reserved.
* $Id$
*
*/

require_once(realpath(dirname(__FILE__)) . '/classes/Account.php');
require_once(realpath(dirname(__FILE__)) . '/common/ServiceFactory.php');

/**
 * Quản lý việc chứng thực user
 */
class AuthenticationService 
{

    /**
     * @ReturnType Boolean
     * @ParamType user 
     * Kiểm tra user đã đăng nhập hay chưa
     */
    public function isAuthenticated() 
    {
        return $this -> getCurrentUser() != null;
    }

    /**
     * @ReturnType classes.Account
     * Lấy user hiện tại
     */
    public function getCurrentUser() 
    {
        $username = '';
        if(isset($_SESSION['user']))
            $username = $_SESSION['user'];
        
        try
        {
            $user = ServiceFactory::get("UserService")->findUserByName($username);
            return $user;
        }
        catch(Exception $ex){}
        
        return null;
    }

    /**
     * @ReturnType void
     * @ParamType user 
     * login user
     */
    public function login($user) 
    {
        if($user)
        {
            $_SESSION['user'] = $user -> getNickname();
            return true;
        }
        
        return false;
    }

    /**
     * @ReturnType void
     * @ParamType user 
     * logout user
     */
    public function logout($user, $backPage = "") 
    {
        unset($_SESSION['user']);
        $_SESSION = array();
        
        Response::redirect((empty($backPage))?$this -> loginPage($user):$backPage);
    }
    
    public function loginPage($user, $admin=false)
    {
        if(!$this -> isUser($user) || $admin)
        {
            return ServiceFactory::get("SystemConfiguration") -> getSetting("site-url") . "/admin/login.php";
        }
        else
        {
            return ServiceFactory::get("SystemConfiguration") -> getSetting("site-url") . "/";
        }
    }
    
    public function isSuperAdministrator($user)
    {
        $role = ServiceFactory::get("UserService") -> getUserRole($user -> getID());
        return $role -> getRoleName() == "Administrator";
    }
    
    public function isManager($user)
    {
        $role = ServiceFactory::get("UserService") -> getUserRole($user -> getID());
        return $role -> getRoleName() == "Manager";
    }
    
    public function isUser($user)
    {
        $role = ServiceFactory::get("UserService") -> getUserRole($user -> getID());
        return $role -> getRoleName() == "User";
    }
    
    public function currentUserCan()
    {
        $user = $this -> getCurrentUser();
        return !$this -> isUser($user);
    }
}

?>